//
//  MBDReactNativeViewController.swift
//  MasterBoy
//
//  Created by Claude on 2025/11/13.
//

// 在文件顶部添加
#if compiler(>=5.9)
#warning("RCTRootView is deprecated but still recommended for Brownfield apps in RN 0.82")
#endif

import UIKit
import React

class MBDReactNativeViewController: UIViewController, RCTBridgeDelegate {

    private var bridge: RCTBridge?
    private var rootView: RCTRootView?

    override func viewDidLoad() {
        super.viewDidLoad()

        // 设置导航栏
        self.title = "React Native"
        self.view.backgroundColor = .white

        // 加载 React Native 视图
        loadReactNativeView()
    }

    private func loadReactNativeView() {
        // 创建 bridge（使用新架构）
        bridge = RCTBridge(delegate: self, launchOptions: nil)
        

        // 创建 RCTRootView
        rootView = RCTRootView(
            bridge: bridge!,
            moduleName: "MasterBoyRN",
            initialProperties: nil
        )

        // 设置 rootView 的frame
        if let rootView = rootView {
            rootView.frame = self.view.bounds
            rootView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

            // 添加到视图层级
            self.view.addSubview(rootView)
        }
    }

    // MARK: - RCTBridgeDelegate

    func sourceURL(for bridge: RCTBridge) -> URL? {
        return getBundleURL()
    }

    private func getBundleURL() -> URL? {
        #if DEBUG
        // 开发模式：从 Metro bundler 加载
        // 确保 Metro bundler 正在运行 (npm start)
        return RCTBundleURLProvider.sharedSettings().jsBundleURL(
            forBundleRoot: "index"
        )
        #else
        // 生产模式：从应用 bundle 加载
        // 需要先构建 JavaScript bundle
        return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
        #endif
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // 隐藏导航栏（可选）
        // self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }
}
